rm(list=ls())
library(statnet)
setwd("C:\\Documents and Settings\\Laura Metzger\\Desktop\\Dissertation\\Chapter2\\Data\\")
data<-read.csv("NC97.csv")
load("NCnet97.RData")

diag(AM)<-0
AM<-AM[-124,-124]

AMnet<-network(AM)
r<-as.vector(AM)
r<-r[r!=0]
set.edge.attribute(AMnet, "values", r, e=1:length(r))
AMnet<-network.adjacency(AM, AMnet, ignore.eval=FALSE, names.eval="values")
get.edge.attribute(AMnet$mel, "values")

same.party<-matrix(0, 123, 123)
for(i in 1:123){
for(j in 1:123){
same.party[i,j]<-ifelse(data$party[i]==data$party[j], 1, 0)
}
}

same.dist<-matrix(0, 123, 123)
for(i in 1:123){
for(j in 1:123){
same.dist[i,j]<-ifelse(data$district[i]==data$district[j], 1, 0)
}
}
same.dist<-ifelse(is.na(same.dist)==TRUE, 0, same.dist)

diag(same.dist)<-0

a<-as.vector(same.party)
b<-as.vector(same.dist)
c<-a*b

interact<-matrix(c, ncol=123)



mod<-ergmm(AMnet~latentcov(same.party)+latentcov(same.dist)+latent(d=2), family="Poisson", response="values", verbose=1)
dput(mod, file="results97.txt")
dput(summary(mod), file="summary97.txt")
summary(mod)

r<-predict.ergmm(mod)
f<-AM-r

pdf("DensityDifference97.pdf")
plot(density(f), main="Density of Differences between Observed and Predicted Connections", xlab="Difference in Connections")
dev.off()

pdf("DensityObsPre97.pdf")
plot(density(AM), col="red", xlim=c(-5, 20), main="Density of Observed and Predicted Connections in the NC House")
lines(density(r), col="blue", xlim=c(-5, 20))
legend(10, 0.25, c("Observed","Predicted"), col=c("red", "blue"), lty=c(1,1))
dev.off()

pdf("positions97.pdf")
plot(mod, vertex.col=party+1, main="MKL Latent Positions of NC House in 1997", label=TRUE, edge.col=0, what="mkl")
abline(0,0)
abline(v=0)
legend(-5, 6, c("Democrats","Republicans"), col=c("red","black"), lty=c(1,1), lwd=c(2,2))
dev.off()
